//router官方说明：https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
//进度条依赖：https://www.npmjs.com/package/nprogress
//路由鉴权:鉴权，项目当中路由能不能被的权限的设置
import router from '@/router'
//@ts-ignore 忽略ts文件检测
import NProgress from 'nprogress/nprogress.js'
import 'nprogress/nprogress.css'
//src外围需要引入大仓库
import pinia from './store'
import useUserStore from './store/modules/user'
import setting from './setting'

const userStore = useUserStore(pinia)

//全局守卫：项目当中任意路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to: any, _from: any, next: any) => {
  //next:路由的放行函数

  //取消转动加载效果
  NProgress.configure({ showSpinner: false })
  //导航标题
  document.title = `${setting.title}-${to.meta.title}`
  NProgress.start()
  if (userStore.token) {
    //登录成功访问login。不能访问
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (userStore.userName) {
        next()
      } else {
        try {
          //获取用户信息
          await userStore.getUserInfo()
          next()
        } catch (error) {
          //token过期或者被修改
          userStore.useLogOut()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //访问路由是否为登录的路由
    if (to.path == '/login') {
      next()
    } else {
      //向路由参数对象放入redirect，用于登录重定向回去
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
//全局前置守卫
router.afterEach((_to: any, _from: any) => {
  NProgress.done()
})
